#include "Socket.hpp"
#include <sys/wait.h>
#include <functional>

using namespace SocketModule;

using ioservice_t = std::function<void(std::shared_ptr<Socket> &, InetAddr &)>;

class TcpServer : public NoCopy
{
public:
    TcpServer(uint16_t port, ioservice_t service)
        : _port(port), _listensockfd(std::make_unique<TcpSocket>()), _isrunning(false), _service(service)
    {
        _listensockfd->BuildTcpSocketMethod(_port);
    }

    void Run()
    {
        if (_isrunning)
            return;
        _isrunning = true;
        while (_isrunning)
        {
            InetAddr peer;
            std::shared_ptr<Socket> psock = _listensockfd->Accept(&peer);
            if(psock == nullptr)
            {
                continue;
            }
            //多进程方式
            pid_t id = fork();
            if(id < 0)
            {
                LOG(LogLevel::FATAL) << "fork error!";
                exit(FORK_ERR);
            }
            else if(id == 0)
            {
                //child
                _listensockfd->Close();
                if(fork())
                    exit(OK);
                //grandchild
                _service(psock, peer);
                exit(OK);
            }
            else
            {
                //father
                psock->Close();
                int n = waitpid(id, nullptr, 0);
                (void)n;
            }
        }
        _isrunning = false;
    }

private:
    uint16_t _port;
    std::unique_ptr<Socket> _listensockfd;

    bool _isrunning; // 是否运行

    ioservice_t _service;    //io任务
};